package com.whyx.project.openapi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whyx.project.openapi.business.DeviceAlarmData;
import com.whyx.project.openapi.business.FileSaveFinished;
import com.whyx.project.openapi.business.GpsData;
import com.whyx.project.openapi.config.JT808ServerConfig;
import com.whyx.project.openapi.config.KafkaProducerConfig;
import com.whyx.project.openapi.config.RedisConfig;
import com.whyx.project.openapi.handle.FileUploadHandle;
import com.whyx.project.openapi.service.KafkaService;
import com.whyx.project.openapi.util.R;
//import com.whyx.project.openapi.util.SignUtils;
import exsun.jt808.data.base.MsgDirection;
import exsun.jt808.data.config.jt808.Jt808DistributeMsgTopic;
import exsun.jt808.data.config.jt808.Jt808ReceiveMsgTopic;
import exsun.jt808.data.kafka_data.KafkaJT808Data;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@Api(description = "第三方服务的接口")
@Component
public class ServiceController {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private com.whyx.project.openapi.config.JT808ServerConfig JT808ServerConfig;

    @Autowired
    private static KafkaService kafkaService;

    @Resource(name = "HandleCenterKafkaTemplate")
    public KafkaTemplate<String, String> stringkafkaTemplate;
    @Autowired
    com.whyx.project.openapi.config.JT808ServerConfig jt808ServerConfig;


    private final RedisConfig redisConfig;

    @Autowired
    public ServiceController(RedisConfig redisConfig) {
        this.redisConfig = redisConfig;
    }



    @ApiOperation("定位数据接口")
    @CrossOrigin //允许跨域认证
    @PostMapping(value = "/{controllerPath}/gpsController")
    public @ResponseBody R gpsController(@RequestBody GpsData gpsData){
        R r = new R();
        int port = JT808ServerConfig.getJt808ServerPort();
        KafkaJT808Data kafkaJT808Data = new KafkaJT808Data(gpsData,gpsData.dvo,gpsData.mid,gpsData.tpc, MsgDirection.up, port);
        String sendData = kafkaJT808Data.getJsonFromObject();
        kafkaService.push1(gpsData.tpc, kafkaJT808Data.getDevNo(), sendData);
        return r;
    }

    /**
     * 接口接收文件上传时要先将该文件数据存到FTP服务器，再将文件置空后推送，避免文件太大推送出错
     */
    @ApiOperation("文件数据接口")
    @CrossOrigin //允许跨域认证
    @PostMapping(value = "/{controllerPath}/fileController")
    public @ResponseBody
    R fileController(FileSaveFinished fileData){
        R r = new R();
        try {
            byte[] fileBytes = fileData.file.getBytes();
            String filePath = FileUploadHandle.getFilePath(fileData.dvo);
            String fileName = FileUploadHandle.getFileName();
            String path = "ftp://" + jt808ServerConfig.getJt808FtpServer() + ":" + jt808ServerConfig.getJt808FtpPort() + filePath + "/" + fileName;
            logger.info("文件存储至ftp...  {}", path);
            boolean result = false;
            try {
                result = FileUploadHandle.saveToFTP(JT808ServerConfig, fileName, filePath, fileBytes);
            }  catch (Exception e) {
                e.printStackTrace();
            }
            logger.info("文件存储" + (result == true?"成功:":"失败:") + path);
            if (result == true){
                fileData.setFile(null);
                kafkaService.push(fileData.getDvo(), Jt808ReceiveMsgTopic.fileSaveFinished, fileData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return r;
    }



    @ApiOperation("报警数据接口")
    @CrossOrigin //允许跨域认证
    @PostMapping(value = "/{controllerPath}/alarmController")
    public @ResponseBody
    R alarmController(@RequestBody DeviceAlarmData alarmData){
        R r = new R();
        kafkaService.push(alarmData.getDvo(), Jt808ReceiveMsgTopic.DeviceAlarm, alarmData);
        return r;
    }

    @ApiOperation("接收健康码设备返回的结果")
    @CrossOrigin //允许跨域认证
    @PostMapping(value = "/{controllerPath}/healthCodeController")
    public @ResponseBody
    R healthCodeController(@RequestBody String responseStr){
        R r = new R();
        logger.info(responseStr);

        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        String key = String.valueOf(jsonObject.get("requestId"));
        redisConfig.redisTemplate().opsForHash().put("HealthCode",key,responseStr);

        return r;
    }


//    /**
//     * 通过appkey、appSecret调用api接口获取access_token
//     */
//    private static final String openapi_url = "http://open.aichezaixian.com/route/rest";
//
//    // 申请来的appKey和appSecret
//    private static final String app_key = "8FB345B8693CCD00B415E0B989FBB506";
//    private static final String app_secret = "7f9cc4d72c7f4cc1a5870cb1cbc829dd";
//
//    //不同接口对应的method值
//    private static final String getTokenApi = "jimi.oauth.token.get";
//    private static final String getLocationApi = "jimi.device.location.get";
//    private static final String getHistoryTrackApi = "jimi.device.track.list";
//
//
//
//    @Autowired
//    KafkaProducerConfig kafkaProducerConfig;
//
//    /**
//     * 获取token
//     */
//    public static String GetToken() throws IOException {
//        Map<String, String> headerMap = new HashMap<String, String>();
//        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
//
//        Map<String, String> paramMap = new HashMap<String, String>();
//        // 公共参数
//        paramMap.put("app_key", app_key);
//        paramMap.put("v", "1.0");
//        paramMap.put("timestamp", getCurrentDate());
//        paramMap.put("sign_method", "md5");
//        paramMap.put("format", "json");
//        paramMap.put("method", getTokenApi);
//        //paramMap.put("method", "jimi.user.device.location.list");
//
//        // 私有参数
//        paramMap.put("user_id", "北斗时空");
//        paramMap.put("user_pwd_md5", DigestUtils.md5Hex("ABC888888"));
//        paramMap.put("expires_in", "120");
//
//        // 计算签名
//        String sign = "";
//        try {
//            sign = SignUtils.signTopRequest(paramMap, app_secret, "md5");
//            paramMap.put("sign", sign);
//        } catch (IOException e) {
//            System.err.println(e);
//        }
//        return (String) sendPost1(headerMap, paramMap);
//    }
//
//    /**
//     * 根据imei获取实时定位
//     */
////      public static void main(String[] args){
//    public  void getLocation(){
//
//        String token = null;
//        try {
//            token = GetToken();
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        Map<String, String> headerMap = new HashMap<String, String>();
//        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
//
//        Map<String, String> paramMap = new HashMap<String, String>();
//        // 公共参数
//        paramMap.put("app_key", app_key);
//        paramMap.put("v", "1.0");
//        paramMap.put("timestamp", getCurrentDate());
//        paramMap.put("sign_method", "md5");
//        paramMap.put("format", "json");
//        paramMap.put("method", getLocationApi);
//        //paramMap.put("method", "jimi.user.device.location.list");
//
//        // 私有参数
//        paramMap.put("access_token",token);
////        paramMap.put("access_token", "4fffb53c19bba8dbfc32281dcbc6652f");
//        paramMap.put("imeis", "868120270323170");
//        paramMap.put("map_type", "BAIDU");
//
//        // 计算签名
//        String sign = "";
//        try {
//            sign = SignUtils.signTopRequest(paramMap, app_secret, "md5");
//            paramMap.put("sign", sign);
//        } catch (IOException e) {
//            System.err.println(e);
//        }
//        sendPost2(headerMap, paramMap);
//
//    }
//
//    @ApiOperation("实时定位接口")
//    @CrossOrigin //允许跨域认证
//    @GetMapping(value = "/{controllerPath}/getLocation")
//    public @ResponseBody
//    R ceshiController(){
//        String token = null;
//        try {
//            token = GetToken();
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        Map<String, String> headerMap = new HashMap<String, String>();
//        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
//
//        Map<String, String> paramMap = new HashMap<String, String>();
//        // 公共参数
//        paramMap.put("app_key", app_key);
//        paramMap.put("v", "1.0");
//        paramMap.put("timestamp", getCurrentDate());
//        paramMap.put("sign_method", "md5");
//        paramMap.put("format", "json");
//        paramMap.put("method", getLocationApi);
//        //paramMap.put("method", "jimi.user.device.location.list");
//
//        // 私有参数
//        paramMap.put("access_token",token);
////        paramMap.put("access_token", "4fffb53c19bba8dbfc32281dcbc6652f");
//        paramMap.put("imeis", "868120270323170");
//        paramMap.put("map_type", "BAIDU");
//
//        // 计算签名
//        String sign = "";
//        try {
//            sign = SignUtils.signTopRequest(paramMap, app_secret, "md5");
//            paramMap.put("sign", sign);
//        } catch (IOException e) {
//            System.err.println(e);
//        }
//        sendPost2(headerMap, paramMap);
//        return null;
//
//    }
//
//
////    /**
////     * 根据imei获取设备历史轨迹
////     */
////    public void getHistoryTrackList(){
//////        public static void main(String[] args){
////        Map<String, String> headerMap = new HashMap<String, String>();
////        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
////
////        Map<String, String> paramMap = new HashMap<String, String>();
////
////        String token = null;
////        try {
////            token = GetToken();
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
////        // 公共参数
////        paramMap.put("app_key", app_key);
////        paramMap.put("v", "1.0");
////        paramMap.put("timestamp", getCurrentDate());
////        paramMap.put("sign_method", "md5");
////        paramMap.put("format", "json");
////        paramMap.put("method", getHistoryTrackApi);
////        //paramMap.put("method", "jimi.user.device.location.list");
////
////        // 私有参数
////        paramMap.put("access_token", token);
////        paramMap.put("imei", "868120270323170");
////        paramMap.put("begin_time", "2021-10-10 00:00:00");
////        paramMap.put("end_time", "2021-10-19 23:59:59");
////        paramMap.put("map_type", "BAIDU");
////
////        // 计算签名
////        String sign = "";
////        try {
////            sign = SignUtils.signTopRequest(paramMap, app_secret, "md5");
////            paramMap.put("sign", sign);
////        } catch (IOException e) {
////            System.err.println(e);
////        }
////
////        sendPost3(headerMap, paramMap);
////    }
//
//    @ApiOperation("历史轨迹接口")
//    @CrossOrigin //允许跨域认证
//    @GetMapping(value = "/{controllerPath}/getHistoryTrack")
//    public @ResponseBody
//    R historyController(){
//        Map<String, String> headerMap = new HashMap<String, String>();
//        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
//
//        Map<String, String> paramMap = new HashMap<String, String>();
//
//        String token = null;
//        try {
//            token = GetToken();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        // 公共参数
//        paramMap.put("app_key", app_key);
//        paramMap.put("v", "1.0");
//        paramMap.put("timestamp", getCurrentDate());
//        paramMap.put("sign_method", "md5");
//        paramMap.put("format", "json");
//        paramMap.put("method", getHistoryTrackApi);
//        //paramMap.put("method", "jimi.user.device.location.list");
//
//        // 私有参数
//        paramMap.put("access_token", token);
//        paramMap.put("imei", "868120270323170");
//        paramMap.put("begin_time", "2021-10-22 16:00:00");
//        paramMap.put("end_time", "2021-10-22 17:40:00");
//        paramMap.put("map_type", "BAIDU");
//
//        // 计算签名
//        String sign = "";
//        try {
//            sign = SignUtils.signTopRequest(paramMap, app_secret, "md5");
//            paramMap.put("sign", sign);
//        } catch (IOException e) {
//            System.err.println(e);
//        }
//
//        sendPost3(headerMap, paramMap);
//        return null;
//    }
//
//    private static Object sendPost1(Map<String, String> headerMap, Map<String, String> paramMap) throws IOException {
//        HttpPost post = new HttpPost(openapi_url);
//        List<NameValuePair> list = new ArrayList<NameValuePair>();
//        for (String key : paramMap.keySet()) {
//            list.add(new BasicNameValuePair(key, paramMap.get(key)));
//        }
//        post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
//        if (null != headerMap) {
//            post.setHeaders(assemblyHeader(headerMap));
//        }
//
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        HttpResponse response = httpClient.execute(post);
//        HttpEntity entity = response.getEntity();
//        JSONObject tokenJson = JSONObject.parseObject(EntityUtils.toString(entity, "utf-8"));
//        Map<String,String> tokenMap = (Map<String, String>) tokenJson.get("result");
//        System.out.println(tokenMap.get("accessToken"));
//        return tokenMap.get("accessToken");
//    }
//
//    private void sendPost2(Map<String, String> headerMap, Map<String, String> paramMap) {
//        try {
//            HttpPost post = new HttpPost(openapi_url);
//            List<NameValuePair> list = new ArrayList<NameValuePair>();
//            for (String key : paramMap.keySet()) {
//                list.add(new BasicNameValuePair(key, paramMap.get(key)));
//            }
//            post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
//            if (null != headerMap) {
//                post.setHeaders(assemblyHeader(headerMap));
//            }
//
//            CloseableHttpClient httpClient = HttpClients.createDefault();
//            HttpResponse response = httpClient.execute(post);
//            HttpEntity entity = response.getEntity();
//
//            JSONObject tokenJson = JSON.parseObject(EntityUtils.toString(entity, "utf-8"));
//            //List<GpsData> data = JSON.parseArray(tokenJson.getString("result"),GpsData.class);
//            JSONArray data = JSON.parseArray(tokenJson.getString("result"));
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            for (int i = 0 ;i < data.toArray().length; i++ ){
//                JSONObject itemArr = (JSONObject) data.get(i);
//                GpsData gpsData = new GpsData();
//                gpsData.dvo = String.valueOf(itemArr.get("imei"));
//                gpsData.lat = Double.parseDouble(String.valueOf(itemArr.get("lat")));
//                gpsData.lng = Double.parseDouble(String.valueOf(itemArr.get("lng")));
//                if (String.valueOf(itemArr.get("speed")).equals("null")){
//                    gpsData.spd = 0;
//                }else {
//                    gpsData.spd = Integer.valueOf(String.valueOf(itemArr.get("speed")));
//                }
//                if (String.valueOf(itemArr.get("direction")).equals("null")){
//                    gpsData.dre = 0;
//                }else {
//                    gpsData.dre = Integer.valueOf(String.valueOf(itemArr.get("direction")));
//                }
//                gpsData.gdt = sdf.parse(String.valueOf(itemArr.get("gpsTime"))) ;
//                if (String.valueOf(itemArr.get("mileage")).equals("null")){
//                    gpsData.mie = 0;
//                }else {
//                    String number = String.valueOf(itemArr.get("mileage"));
//                    gpsData.mie = Integer.valueOf(number.substring(0,number.indexOf(".")));
//                }
////                gpsData.sts.set(0,(Integer) itemArr.get("accStatus"));
//                System.out.println(gpsData);
//                this.pushData(gpsData.dvo,Jt808ReceiveMsgTopic.gpsData,gpsData);
//            }
//
//        } catch (IOException e) {
//            System.err.println(e);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    private void sendPost3(Map<String, String> headerMap, Map<String, String> paramMap) {
//        try {
//            HttpPost post = new HttpPost(openapi_url);
//            List<NameValuePair> list = new ArrayList<NameValuePair>();
//            for (String key : paramMap.keySet()) {
//                list.add(new BasicNameValuePair(key, paramMap.get(key)));
//            }
//            post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
//            if (null != headerMap) {
//                post.setHeaders(assemblyHeader(headerMap));
//            }
//
//            CloseableHttpClient httpClient = HttpClients.createDefault();
//            HttpResponse response = httpClient.execute(post);
//            HttpEntity entity = response.getEntity();
//            String msg = EntityUtils.toString(entity, "utf-8");
//            JSONObject tokenJson = JSON.parseObject(msg);
//            //List<GpsData> data = JSON.parseArray(tokenJson.getString("result"),GpsData.class);
//            JSONArray data = JSON.parseArray(tokenJson.getString("result"));
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            for (int i = 0 ;i < data.toArray().length; i++ ){
//                JSONObject itemArr = (JSONObject) data.get(i);
//                GpsData gpsData = new GpsData();
//                gpsData.dvo = "868120270323170";
//                gpsData.lat = Double.parseDouble(String.valueOf(itemArr.get("lat")));
//                gpsData.lng = Double.parseDouble(String.valueOf(itemArr.get("lng")));
//                if (String.valueOf(itemArr.get("speed")).equals("null")){
//                    gpsData.spd = 0;
//                }else {
//                    gpsData.spd = Integer.valueOf(String.valueOf(itemArr.get("speed")));
//                }
//                if (String.valueOf(itemArr.get("direction")).equals("null")){
//                    gpsData.dre = 0;
//                }else {
//                    gpsData.dre = Integer.valueOf(String.valueOf(itemArr.get("direction")));
//                }
//                gpsData.gdt = sdf.parse(String.valueOf(itemArr.get("gpsTime"))) ;
//                if (String.valueOf(itemArr.get("mileage")).equals("null")){
//                    gpsData.mie = 0;
//                }else {
//                    String number = String.valueOf(itemArr.get("mileage"));
//                    gpsData.mie = Integer.valueOf(number.substring(0,number.indexOf(".")));
//                }
////                gpsData.sts.set(0,(Integer) itemArr.get("accStatus"));
//                System.out.println(gpsData);
////                service.push( gpsData.dvo,Jt808ReceiveMsgTopic.gpsData, gpsData);
////                kafkaProducerConfig.kafkaTemplate().send(Jt808ReceiveMsgTopic.gpsData, String.valueOf(data));
//                this.pushData(gpsData.dvo,Jt808ReceiveMsgTopic.gpsData,gpsData);
//
//            }
//
//
////            System.out.println(historyTrackList);
//
//
//        } catch (IOException e) {
//            System.err.println(e);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 组装头部信息
//     *
//     * @param headers
//     * @return
//     */
//    private static Header[] assemblyHeader(Map<String, String> headers) {
//        Header[] allHeader = new BasicHeader[headers.size()];
//        int i = 0;
//        for (String str : headers.keySet()) {
//            allHeader[i] = new BasicHeader(str, headers.get(str));
//            i++;
//        }
//        return allHeader;
//    }
//
//    public static String getCurrentDate() {
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String result = formatter.format(new Date());
//        return result;
//    }
//
//    public void pushData(String devNo, String topic, Object data)
//    {
//
//        int port = jt808ServerConfig.getJt808ServerPort();
//        KafkaJT808Data kafkaJT808Data = new KafkaJT808Data(data, devNo,0, topic, MsgDirection.up,port);
//
//        String sendData = kafkaJT808Data.getJsonFromObject();
//
//        stringkafkaTemplate.send(topic, kafkaJT808Data.getDevNo(), sendData);
//        //logger.info("kafka 推送信息----" + data.getTpc() + "--解析时间--" + data.getPte() + "--设备号--" + data.dvo);
//    }
//
//




}
